package com.pdd.controller;

import com.pdd.beans.Address;
import com.pdd.dto.DTO;
import com.pdd.service.AddressService;
import com.pdd.vo.address.AddressVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址控制器
 */
@Api(description = "地址地址接口",tags = {"用户地址接口"})
@CrossOrigin(origins = { "*" })
@Controller
public class AddressController {
    @Autowired
    @Setter
    private AddressService addressService;

    @ApiOperation(value = "添加地址信息")
    @RequestMapping(value = "/address", method = RequestMethod.POST)
    @ResponseBody
    public DTO addUser(AddressVO vo){
        // 1. 封装参数
        Address address = new Address();
        address.setU_id(vo.getU_id());
        address.setAddress(vo.getAddress());
        address.setCode(vo.getCode());
        address.setName(vo.getName());
        address.setTel(vo.getTel());

        // 2. 执行新增
        boolean result = addressService.addAddress(address);

        // 3. 创建DTO，并返回
        if (result){
            return DTO.success();
        }else{
            return DTO.error();
        }
    }
    @ApiOperation(value = "删除地址")
    @RequestMapping(value = "/address/{id}", method = RequestMethod.DELETE)
    public DTO delUser(@PathVariable(value = "id") Integer id){

        boolean result = addressService.delAddress(id);
        if (result){
            return DTO.success();
        }else {
            return DTO.error();
        }
    }

    @ApiOperation(value = "更新地址信息")
    @RequestMapping(value = "/address", method = RequestMethod.PUT)
    @ResponseBody
    public DTO uplUser(AddressVO vo){
        // 1. 封装参数
        Address address = new Address();
        address.setU_id(vo.getU_id());
        address.setAddress(vo.getAddress());
        address.setCode(vo.getCode());
        address.setName(vo.getName());
        address.setTel(vo.getTel());
        // 2. 执行更新
        boolean result = addressService.uplAddress(address);

        // 3. 创建DTO，并返回
        if (result){
            return DTO.success();
        }else{
            return DTO.error();
        }
    }

    @ApiOperation(value = "查询用户信息")
    @RequestMapping(value = "/address", method = RequestMethod.GET)
    @ResponseBody
    public DTO getUser(){
        // 1. 执行查询操作
        List<Address> list = addressService.getAddress();

        // 2. 封装 DTO
        DTO dto = new DTO(list);

        // 3. 返回结果
        return dto;
    }
    @ApiOperation(value = "根据ID查询地址信息")
    @RequestMapping(value = "/address/{id}", method = RequestMethod.GET)
    @ResponseBody
    public DTO getById(@PathVariable(value = "id") Integer id){
        // 1. 执行查询操作
        Address list = addressService.getById(id);

        // 2. 封装 DTO
        DTO dto = new DTO(list);

        // 3. 返回结果
        return dto;
    }
}